package com.lesso.lpq.sunflower.infra.repository.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.lesso.lpq.sunflower.domain.repository.DeviceRepository;
import com.lesso.lpq.sunflower.infra.assembler.DeviceAssembler;
import com.lesso.lpq.sunflower.infra.mapper.DeviceMapper;
import com.lesso.lpq.sunflower.model.Device;
import com.lesso.lpq.sunflower.pojo.dto.DeviceQueryDTO;
import com.lesso.lpq.sunflower.pojo.vo.DeviceVO;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @ClassName : DeviceRepositoryImpl
 * @Description :
 * @Author : 罗培棋
 * @Date: 2025-07-05 10:01
 */
@Repository
public class DeviceRepositoryImpl implements DeviceRepository {

    private final DeviceMapper deviceMapper;
    public DeviceRepositoryImpl(DeviceMapper deviceMapper) {
        this.deviceMapper = deviceMapper;
    }

    @Override
    public Long save(Device device) {
        device.setDelStatus(0);
        deviceMapper.insert(device);
        return device.getId();
    }

    @Override
    public Page<DeviceVO> getPageList(DeviceQueryDTO dto) {
        Page<DeviceVO> page = new Page<>(dto.getCurrent(), dto.getSize());
        EntityWrapper<Device> wrapper = new EntityWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getDeviceName()), "deviceName", dto.getDeviceName());
        List<Device> devices = deviceMapper.selectPage(page, wrapper);
        return page.setRecords(DeviceAssembler.INSTANCE.entityListToVOList(devices));
    }

    @Override
    public Page<DeviceVO> getCustomPageList(DeviceQueryDTO dto) {
        Page<DeviceVO> page = new Page<>(dto.getCurrent(), dto.getSize());
        List<DeviceVO> list = deviceMapper.selectPageList(page,dto);
        return page.setRecords(list);
    }

    @Override
    public void removeById(Long id) {
        deviceMapper.deleteById(id);
    }

    @Override
    public DeviceVO getByDeviceCode(String deviceCode) {
        EntityWrapper<Device> wrapper = new EntityWrapper<>();
        wrapper.eq("device_code", deviceCode);
        wrapper.eq("del_status", 0);
        List<Device> devices = deviceMapper.selectList(wrapper);
        if (devices == null || devices.isEmpty()) {
            return null;
        }
        return DeviceAssembler.INSTANCE.entityToVO(devices.get(0));
    }
}
